package com.thread.test20180827.lock;


import org.junit.Test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 测试juc下的Lock类
 * <p>
 * void lock();
 * void lockInterruptibly() throws InterruptedException;
 * boolean tryLock();
 * boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
 * void unlock();
 * Condition newCondition();
 * @author: conceit
 * @Date: 2018/8/27  13:57
 */
public class LockTest implements Runnable {

    //定义票
    private int tickets = 100;

    /**
     * @Description:
     * @author: conceit
     * @Date: 2018/8/27 0027 14:21
     */
    Lock lock = new ReentrantLock();


    @Override
    public void run() {

        while (true) {
            try {
                lock.lock();
                //加锁
                if (tickets > 0) {
                    //如果注释掉Thread.sleep(100)，则最先调用的线程会一直调用
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

                    }
                    System.out.println(Thread.currentThread().getName() + "正在出售" + --tickets + "张票！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }
}
